<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>pid比例积分微分算法</title>
</head>

<body>
    <div id="motor"></div>
    <script>
        const targetVal = 2000 // 目标值

        /* v2 */
        const PID = curVal => {
            let diff = 0 // 偏差值
            const kP = 0.1

            /*计算目标值与实际值的误差*/
            diff = targetVal - curVal

            let P = diff * kP
            /*PID算法实现*/
            let numPI = Math.abs(P)

            if (P <= 40) {
                numPI += 5
            } else {
                numPI -= 5
            }
            if (curVal + numPI < targetVal) {
                curVal += numPI
            } else {
                curVal -= numPI
            }
            return curVal
        }
        /* test demo*/
        class Motor {
            constructor() {
                this.s = 0
            }
            show() {
                motor.textContent = '当前速度' + this.speed
            }
            set speed(val) {
                this.s = val
            }
            get speed() {
                return Math.random() < 0.5 ? this.s - 5 : this.s + 5
            }
        }
        let m = new Motor()
        m.speed = 0

        setInterval(() => { // start
            let mSpeed = m.speed
            console.log('mSpeed =====' + mSpeed);

            let res = PID(mSpeed)
            console.log('PID =====' + res);

            m.speed = res
            m.show()
        }, 100)
    </script>
</body>

</html>